import React from 'react';
import {inject, observer} from 'mobx-react';
import {toJS, observable, autorun} from 'mobx';
import {WeaTable, WeaTableEditable, WeaTools, WeaDialog, WeaSearchGroup, WeaInput, WeaFormItem, 
    WeaDropdown, WeaSelect, WeaDatePicker, WeaTransfer, WeaCheckbox, WeaBrowser, WeaOrgTree, WeaLocaleProvider} from 'ecCom';
import {Button, Row, Menu, Switch, Input, message} from "antd";

import './style/';

const getLabel = WeaLocaleProvider.getLabel;

@inject("ReportElementSettingStore", "StringUtilsStore")
@observer
class Setting extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            columns: [
                {
                    title: getLabel(508544, "标题"),
                    dataIndex: 'title',
                    key: 'title',
                    com: [
                        {
                            type: 'INPUT', 
                            viewAttr: 1, 
                            key: 'title', 
                            width: 120 
                        }
                    ]
                },
                {
                    title: getLabel(30585, "操作"),
                    dataIndex: 'operation',
                    key: 'operation',
                    com: [
                        {
                            type: 'CUSTOM', 
                            viewAttr: 1, 
                            key: 'operation', 
                            width: 120, 
                            render: (text, record, index, onEdit) => {
                                return (
                                    <span>
                                        <span id={`common-click-set-${index}`} className="common-click-workrelate" onClick={this.handleSetSpanClick}>{getLabel(30747, "设置")}</span>
                                        &nbsp;&nbsp;
                                        <span id={`common-click-othersave-${index}`} className="common-click-workrelate" onClick={this.handleOtherSaveSpanClick}>{getLabel(506965, "另存为")}</span>
                                    </span> 
                                )
                            }
                      }
                    ]
                }
            ],
            tableDatas: []
        };
        // 将当前组件实例传递到元素组件，以便元素组件获取到该组件
        props.getInstance && props.getInstance(this);
    }

    componentWillMount () {
        // 获取元素设置数据
        const {params = {}, ReportElementSettingStore, StringUtilsStore} = this.props;
        const {eid} = params;

        WeaTools.callApi("/api/workrelate/plan/accessAssessmentCycle", "GET", {}).then((result) => {
            let options = []
            if (result && result.stabList) {
                result.stabList.sort((a, b) => {
                    return a.viewcondition - b.viewcondition
                }).forEach((d, i) => {
                    options.push({
                        key: "2-" + d.key,
                        showname: d.title
                    })
                })
            }
            options = options.length> 0 ? options : [{key: "", showname: ""}]
            ReportElementSettingStore.changeReportDateRangeValues2Options(options)

            WeaTools.callApi('/api/workrelate/portal/element/getSettingData', 'GET', {eid}).then((result) => {
                if (result) {
                    let tableDatas = [];
                    for (let k in result) {
                        const {tabseq, title, selectedBigType, orderby, showCount, reportDateRangeValue1, reportDateRangeValue2,
                            reportDateRangeValue3, selectedReportStatus, selectedReportType, reportPersonsStr,
                            selectedSubDepOption, reportSubDepStr, selectedDepOption, reportDepStr} = result[k]
                        tableDatas.push({
                            id: tabseq,
                            title,
                            selectedBigType,
                            orderby,
                            showCount,
                            reportDateRangeValue1,
                            reportDateRangeValue2,
                            reportDateRangeValue3,
                            selectedReportStatus,
                            selectedReportType,
                            reportPersonsStr,
                            selectedSubDepOption,
                            reportSubDepStr,
                            selectedDepOption,
                            reportDepStr
                        })
                    }
    
                    // 设置默认数据
                    // if (tableDatas.length == 0) {
                    //     let defaultTableDatas = toJS(ReportElementSettingStore.defaultTableDatas)
                    //     if (Array.isArray(defaultTableDatas)) {
                    //         defaultTableDatas.forEach((d, i) => {
                    //             d.reportDateRangeValue2 = ReportElementSettingStore.reportDateRangeValues2Options[0].key
                    //             tableDatas.push(d)
                    //         })
                    //     }
                    // }
    
                    this.setState({
                        tableDatas
                    })
                }
            });
        })
    }

    handleSetSpanClick = (e) => {
        const {ReportElementSettingStore} = this.props
        ReportElementSettingStore.selectedTableDataId = e.target.id.substring(e.target.id.lastIndexOf("-") + 1)
        ReportElementSettingStore.contentSettingDialogVisibleMethod = "set"
        ReportElementSettingStore.changeContentSettingDialogVisible(true)
        ReportElementSettingStore.setContentSettingDialog(this.state.tableDatas[parseInt(ReportElementSettingStore.selectedTableDataId)])
    }

    handleOtherSaveSpanClick = (e) => {
        const {ReportElementSettingStore} = this.props
        ReportElementSettingStore.selectedTableDataId = e.target.id.substring(e.target.id.lastIndexOf("-") + 1)
        ReportElementSettingStore.contentSettingDialogVisibleMethod = "othersave"
        ReportElementSettingStore.changeContentSettingDialogVisible(true)
        ReportElementSettingStore.setContentSettingDialog(this.state.tableDatas[parseInt(ReportElementSettingStore.selectedTableDataId)])
    }

    onDialogSureClick = () => {
        const {ReportElementSettingStore, StringUtilsStore} = this.props
        if (!StringUtilsStore.allIsNotEmpty(ReportElementSettingStore.tabTitle, 
            ReportElementSettingStore.selectedBigType, ReportElementSettingStore.reportDateRangeValue2)) {
            message.warning(getLabel(15859 , "必要信息不完整！"))
            return
        }

        ReportElementSettingStore.changeContentSettingDialogVisible(false)

        let currTableData = {
            //id: ReportElementSettingStore.tableDatas.length,
            title: ReportElementSettingStore.tabTitle,
            selectedBigType: ReportElementSettingStore.selectedBigType,
            orderby: ReportElementSettingStore.orderby,
            showCount: ReportElementSettingStore.showCount,
            reportDateRangeValue1: ReportElementSettingStore.reportDateRangeValue1,
            reportDateRangeValue2: ReportElementSettingStore.reportDateRangeValue2,
            reportDateRangeValue3: ReportElementSettingStore.reportDateRangeValue3,
            selectedReportStatus: ReportElementSettingStore.showReportStatusSetting ? ReportElementSettingStore.selectedReportStatus : "",
            selectedReportType: ReportElementSettingStore.showReportTypeSetting ? ReportElementSettingStore.selectedReportType : "",
            reportPersonsStr: ReportElementSettingStore.showReportPersonsSetting ? ReportElementSettingStore.reportPersonsStr : "",
            selectedSubDepOption: ReportElementSettingStore.showReportSubDepSetting ? ReportElementSettingStore.selectedSubDepOption : "",
            reportSubDepStr: ReportElementSettingStore.showReportSubDepSetting ? ReportElementSettingStore.reportSubDepStr : "",
            selectedDepOption: ReportElementSettingStore.showReportDepSetting ? ReportElementSettingStore.selectedDepOption : "",
            reportDepStr: ReportElementSettingStore.showReportDepSetting ?  ReportElementSettingStore.reportDepStr : ""
        }

        if (ReportElementSettingStore.contentSettingDialogVisibleMethod == "add" || ReportElementSettingStore.contentSettingDialogVisibleMethod == "othersave") {
            this.state.tableDatas.push(Object.assign({id: this.state.tableDatas.length}, currTableData))
        } else if (ReportElementSettingStore.contentSettingDialogVisibleMethod == "set") {
            let selectedTableDataId = parseInt(ReportElementSettingStore.selectedTableDataId)
            this.state.tableDatas[selectedTableDataId] = Object.assign({id: selectedTableDataId}, currTableData)
        } 
        this.setState({
            tableDatas: this.state.tableDatas
        })
    }

    onDialogCancleClick = () => {
        const {ReportElementSettingStore} = this.props
        ReportElementSettingStore.changeContentSettingDialogVisible(false)
    }

    onAddBtnClick = () => {
        const {ReportElementSettingStore} = this.props
        ReportElementSettingStore.contentSettingDialogVisibleMethod = "add"
        ReportElementSettingStore.changeContentSettingDialogVisible(true)
        ReportElementSettingStore.setDefaultContentSettingDialog()
    }

    onDelBtnClick = (datas, keys) => {
        const {ReportElementSettingStore} = this.props

        keys.sort((a, b) => {
            return b - a
        }).forEach((d, i) => {
            this.state.tableDatas.splice(d, 1)
        })

        // 重新设置数据主键
        this.state.tableDatas.map((item, index) => {
            item.id = index;
        })

        this.setState({
            tableDatas: this.state.tableDatas
        })
    }

    onGroupbyIconClick = () => {
        const {ReportElementSettingStore} = this.props
        ReportElementSettingStore.initOrderbyTransferDatas()
        ReportElementSettingStore.changeOrderbyTransferDialogVisible(true)
    }

    onDataSequenceChange = (datas, other) => {
        const {ReportElementSettingStore} = this.props
        datas.map((item, index) => {
            item.id = index;
        })

        this.setState({
            tableDatas: datas
        })
    }

    onOrderbyTransferDialogSureClick = () => {
        const {ReportElementSettingStore} = this.props
        let orderby = ""

        ReportElementSettingStore.orderbyTransferSelectedKeys.forEach((d, i) => {
            ReportElementSettingStore.orderbyTransferDatas.forEach((dd, ii) => {
                if (d == dd.id) {
                    orderby += (dd.name + "-" + dd.orderType + ",")
                }
            })
        })

        if (orderby != "") {
            orderby = orderby.substring(0, orderby.length - 1)
        }

        ReportElementSettingStore.changeOrderby(orderby)
        ReportElementSettingStore.changeOrderbyTransferDialogVisible(false)
    }

    onOrderbyTransferDialogCancleClick = () => {
        const {ReportElementSettingStore} = this.props
        ReportElementSettingStore.changeOrderbyTransferDialogVisible(false)
        ReportElementSettingStore.initOrderbyTransferDatas()
    }

    render () {
        const {columns} = this.state
        const {ReportElementSettingStore, StringUtilsStore} = this.props

        // dialog内容的设置
        let dialogContent = (
            <div>
                <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@tylttf`} title = {getLabel(82751, "基础设置")} showGroup = {true}>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@jxutgc`}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ofka2l`}
                            style = {{marginLeft: 30}}
                            label={getLabel(508544, "标题")}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{position: "relative", width: "100%"}}>
                                <div style={{width: "90%", height: "100%", display: "inline-block", verticalAlign: "middle"}}>
                                    <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@iycsic`} 
                                        viewAttr={3}
                                        value={ReportElementSettingStore.tabTitle} 
                                        onChange={(value) => {
                                            ReportElementSettingStore.changeTabTitle(value)
                                        }}
                                    />
                                </div>
                            </div>
                        </WeaFormItem>
                    </Row>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@9b4x5t`}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@vjruik`}
                            style = {{marginLeft: 30}}
                            label={getLabel(15512, "排序字段")}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{paddingTop: "7px"}}>
                                <i className="icon-coms-Flow-setting icon-coms-Flow-setting-hover-workrelate" 
                                   onClick={this.onGroupbyIconClick}
                                />
                                <span style={{paddingLeft: "6px"}}>{ReportElementSettingStore.orderby}</span>
                            </div>
                        </WeaFormItem>
                    </Row>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@kcwz4q`}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@rlmo74`}
                            style = {{marginLeft: 30}}
                            label={getLabel(128851, "显示总数")}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{paddingTop: "6px"}}>
                                <Switch ecId={`${this && this.props && this.props.ecId || ''}_Switch@7rwwrb`} 
                                    size={"small"}
                                    checked={ReportElementSettingStore.showCount == "1"} 
                                    onChange={(value) => {
                                        ReportElementSettingStore.showCount = value ? "1" : "0"
                                    }}
                                />
                            </div>
                        </WeaFormItem>
                    </Row>
                </WeaSearchGroup>
                <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@ue3nhm`} title = {getLabel(127253, "来源设置")} showGroup = {true}>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@m71uso`}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@2z5sf9`}
                            style = {{marginLeft: 30}}
                            label={getLabel(16850, '类别')}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{position: "relative", width: "100%"}}>
                                <div style={{width: "90%", height: "100%", display: "inline-block", verticalAlign: "middle"}}>
                                    <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@uuoios`} 
                                        options = {ReportElementSettingStore.bigTypeOptions}
                                        viewAttr={3}
                                        value = {ReportElementSettingStore.selectedBigType}
                                        onChange = {(v) => {ReportElementSettingStore.selectedBigType = v}}
                                    />
                                </div>
                            </div>
                        </WeaFormItem>
                    </Row>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@chwxrx`}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@vb3psr`}
                            style = {{marginLeft: 30}}
                            label={getLabel(15386, '周期')}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{position: "relative", width: "100%"}}>
                                <div style = {{width: "90%", height: "100%", display: "inline-block", verticalAlign: "middle"}}>
                                    <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@5njmgf`} 
                                        viewAttr={3}
                                        options = {ReportElementSettingStore.reportDateRangeValues2Options}
                                        value = {ReportElementSettingStore.reportDateRangeValue2}
                                        onChange = {(value) => {
                                            ReportElementSettingStore.changeReportDateRangeValue2(value)
                                            ReportElementSettingStore.changeReportDateRangeValue3("")
                                        }}
                                    />
                                </div>
                            </div>
                        </WeaFormItem>
                    </Row>
                    {ReportElementSettingStore.showReportStatusSetting ? 
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@iy02uq`}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@26c4e5`}
                            style = {{marginLeft: 30}}
                            label={getLabel(23247, "状态")}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{width: "90%", height: "100%", display: "inline-block", verticalAlign: "middle"}}>
                                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@6imhng`} 
                                    multiple
                                    options={ReportElementSettingStore.reportStatusOptions}
                                    viewAttr={2}
                                    value = {ReportElementSettingStore.selectedReportStatus}
                                    onChange={(v) => {ReportElementSettingStore.changeSelectedReportStatus(v)}}
                                >
                                </WeaSelect> 
                            </div>
                        </WeaFormItem>
                    </Row>
                    : ""
                    }
                    {/* {ReportElementSettingStore.showReportPersonsSetting ? 
                    <Row>
                        <WeaFormItem
                            style = {{marginLeft: 30}}
                            label={"人员"}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{width: "90%", height: "100%", display: "inline-block", verticalAlign: "middle"}}>
                                <WeaBrowser 
                                    type = {17}
                                    isSingle = {false}
                                    replaceDatas = {ReportElementSettingStore.reportPersonsObj}
                                    onChange={(ids, names, datas) => {ReportElementSettingStore.changeReportPersonsStr(ids, names)}}
                                />
                            </div>
                        </WeaFormItem>
                    </Row>
                    : ""
                    }
                    {ReportElementSettingStore.showReportSubDepSetting ? 
                    <Row>
                        <WeaFormItem
                            style = {{marginLeft: 30}}
                            label={"分部"}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{width: "90%", height: "100%", display: "inline-block", verticalAlign: "middle"}}>
                                <div style={{width: "40%", display: "inline-block", verticalAlign: "middle", paddingRight: "20px"}}>
                                    <WeaSelect 
                                        options = {ReportElementSettingStore.reportSubDepOptions}
                                        value = {ReportElementSettingStore.selectedSubDepOption}
                                        onChange = {(value) => {ReportElementSettingStore.changeSelectedSubDepOption(value)}}
                                    />
                                </div>
                                <div style={{width: "60%", display: "inline-block", verticalAlign: "middle"}}>
                                    <WeaBrowser 
                                        type = {164}
                                        replaceDatas = {ReportElementSettingStore.reportSubDepObj}
                                        onChange={(ids, names, datas) => {ReportElementSettingStore.changeReportSubDepStr(ids, names)}}
                                    />
                                </div>
                            </div>
                        </WeaFormItem>
                    </Row>
                    : ""
                    }
                    {ReportElementSettingStore.showReportDepSetting ?
                    <Row>
                        <WeaFormItem
                            style = {{marginLeft: 30}}
                            label={"部门"}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{width: "90%", height: "100%", display: "inline-block", verticalAlign: "middle"}}>
                                <div style={{width: "40%", display: "inline-block", verticalAlign: "middle", paddingRight: "20px"}}>
                                    <WeaSelect 
                                        options = {ReportElementSettingStore.reportDepOptions}
                                        value = {ReportElementSettingStore.selectedDepOption}
                                        onChange = {(value) => {ReportElementSettingStore.changeSelectedDepOption(value)}}
                                    />
                                </div>
                                <div style={{width: "60%", display: "inline-block", verticalAlign: "middle"}}>
                                    <WeaBrowser 
                                        type = {4}
                                        replaceDatas = {ReportElementSettingStore.reportDepObj}
                                        onChange={(ids, names, datas) => {ReportElementSettingStore.changeReportDepStr(ids, names)}}
                                    />
                                </div>
                            </div>
                        </WeaFormItem>
                    </Row>
                    : ""
                    } */}
                </WeaSearchGroup>
            </div>
        )

        // 排序Dialog内容的设置
        let orderbyTransferDialogContent = (
            <div style={{width: "600px", margin: "0 auto"}}>
                <WeaTransfer ecId={`${this && this.props && this.props.ecId || ''}_WeaTransfer@gjwic0`} 
                    data = {ReportElementSettingStore.orderbyTransferDatas}
                    height = {300}
                    selectedKeys = {
                        ReportElementSettingStore.orderbyTransferSelectedKeys
                    }
                    onChange = {(keys, datas) => {
                        let orderbyTransferDatas = toJS(ReportElementSettingStore.orderbyTransferDatas)

                        orderbyTransferDatas.forEach((d, i) => {
                            if (keys.join(",").indexOf(d.id + "") == -1) {
                                d.orderType = "";
                            } else {
                                if (d.orderType == "") {
                                    d.orderType = getLabel(384984, "降序")
                                }
                            }
                        })
                        ReportElementSettingStore.changeOrderbyTransferDatas(orderbyTransferDatas)
                        ReportElementSettingStore.changeOrderbyTransferSelectedKeys(keys)
                    }}
                    renderItem = {(item) => {
                        return (
                            <div style={{height: 37, lineHeight: "37px", borderBottom: "1px solid rgb(226,226,226)", position: "relative"}}>
                                <span style={{paddingLeft: "10px", display: "inline-block"}}>{item.name}</span>
                                <span 
                                    style={{position: "absolute", top: "0px", right: "10px", display: "inline-block"}} 
                                    onClick={(e) => {
                                            e.preventDefault()
                                            e.stopPropagation()
                                            let orderbyTransferDatas = toJS(ReportElementSettingStore.orderbyTransferDatas)
                                            orderbyTransferDatas.forEach((d, i) => {
                                                if (d.id == item.id) {
                                                    d.orderType = (item.orderType == getLabel(384985, "升序") ? getLabel(384984, "降序") : getLabel(384985, "升序"))
                                                }
                                            })
                                            ReportElementSettingStore.changeOrderbyTransferDatas(orderbyTransferDatas)
                                        }
                                    }
                                >
                                    {item.orderType}
                                </span>
                            </div>
                        )
                    }}
                />
            </div>
        )

        return (
            <div className="portal-report-element-setting">
                <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@gjolak`}
                    rowKey = {"id"}
                    datas = {this.state.tableDatas}
                    // title = {getLabel(20885, "内容来源")}
                    title = ""
                    draggable = {true}
                    columns = {columns}
                    showCopy = {false}
                    willAdd = {this.onAddBtnClick}
                    willDelete = {this.onDelBtnClick}
                    onChange = {this.onDataSequenceChange}
                />
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@ys8zg3`} 
                    hasScroll = {true}
                    visible = {ReportElementSettingStore.contentSettingDialogVisible}
                    title = {getLabel(506919, "内容设置")}
                    buttons = {
                        [
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4dxlqf@sure`} type="primary" onClick={this.onDialogSureClick}>
                              {getLabel(826, '确定')}
                            </Button>,
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@jba3l2@cancel`} type="ghost" onClick={this.onDialogCancleClick}>
                              {getLabel(31129, '取消')}
                            </Button>
                        ]
                    }
                    onCancel = {() => {ReportElementSettingStore.changeContentSettingDialogVisible(false)}}
                    children = {dialogContent}
                />
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@l6l7nq`} 
                    style = {{width: 600, height: 300}}
                    visible = {ReportElementSettingStore.orderbyTransferDialogVisible}
                    title = {getLabel(386541, '排序字段设置')}
                    buttons = {
                        [
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@czqvok@sure`} type="primary" onClick={this.onOrderbyTransferDialogSureClick}>
                              {getLabel(826, '确定')}
                            </Button>,
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@hjem3m@cancel`} type="ghost" onClick={this.onOrderbyTransferDialogCancleClick}>
                              {getLabel(31129, '取消')}
                            </Button>
                        ]
                    }
                    onCancel = {this.onOrderbyTransferDialogCancleClick}
                    children = {orderbyTransferDialogContent}
                />
            </div>
        );
    }

    onSave = () => {
        // 保存元素设置数据
        // 如果有必填项，校验不通过时，需要return false;
        const {params = {}, ReportElementSettingStore} = this.props;
        const {eid} = params;
        const {tableDatas} = this.state
        WeaTools.callApi('/api/workrelate/portal/element/saveSettingData', 'POST', {
            tableDatas: JSON.stringify(toJS(tableDatas)),
            eid
        });
    }
}

export default Setting;
